package com.gouwudai.table.view.style1;

import org.extremecomponents.table.bean.Column;
import org.extremecomponents.table.core.TableModel;
import org.extremecomponents.table.view.AbstractHtmlView;
import org.extremecomponents.table.view.html.CalcBuilder;
import org.extremecomponents.table.view.html.RowBuilder;
import org.extremecomponents.util.HtmlBuilder;

public class UserMultiColumnTableView extends AbstractHtmlView {
	private int currentRow=0;
    protected void beforeBodyInternal(TableModel model) {
        getTableBuilder().tableStart();
        //這個加入 <thead>
        getTableBuilder().theadStart();
        
        getTableBuilder().titleRowSpanColumns();

        toolbar(getHtmlBuilder(), getTableModel());
        
        //filter
        getTableBuilder().filterRow();
        
        //這個method加入 欄位名稱
        getTableBuilder().headerRow();
        
        //這個加入 </thead>
        getTableBuilder().theadEnd();
        
        getTableBuilder().tbodyStart();
        currentRow=0;
    }
    
    public void body(TableModel model, Column column) {
    	
    	if (column.isFirstColumn()&& currentRow%getMultiColumn()==0) {
            getRowBuilder().rowStart();
        }
    	
    	getHtmlBuilder().append(column.getCellDisplay());

        if (column.isLastColumn()&& currentRow%getMultiColumn()==(getMultiColumn()-1)) {
        	getRowBuilder().rowEnd();
        }
        
        if (column.isLastColumn()) {	
        	currentRow++;
        }
        
    }
    
    protected void afterBodyInternal(TableModel model) {
    	int cols = model.getColumnHandler().getHeaderColumns().size();
    	int addTime = getMultiColumn()-(currentRow%getMultiColumn());
    	//補缺項讓最後一列整齊
    	if(addTime>0){
    		getHtmlBuilder().td(0).colSpan(""+(cols*addTime));
    		getHtmlBuilder().tdEnd();
    		getRowBuilder().rowEnd();
    	}
    	
        getCalcBuilder().defaultCalcLayout();

        getTableBuilder().tbodyEnd();

        getTableBuilder().tableEnd();
    }
    
    protected void toolbar(HtmlBuilder html, TableModel model) {
        new UserCompactToolbar(html, model).layout();
    }
    protected void init(HtmlBuilder html, TableModel model) {
    	//這裡換成自己的tablebuilder
        setTableBuilder(new UserTableBuilder(html, model));
        setRowBuilder(new RowBuilder(html, model));
        setCalcBuilder(new CalcBuilder(html, model));
    }
    private int getMultiColumn(){
    	String c = getTableModel().getPreferences().getPreference(UserPreferencesConstants.COLUMN_MULTI);
    	if(c==null){
    		//如果沒設定，預設是一欄
    		return 1;
    	}else{
    		return Integer.valueOf(c);
    	}
    }


}
